<template>
    <div class="madp-employee-statistics">
        <div>
            <div class="madp-page-1">
                <el-tree ref="tree" class="filter-tree" :data="treeData" :props="defaultProps" @node-click="handleNodeClick" :expand-on-click-node="false" :default-expand-all="false"></el-tree>
            </div>
            <div class="madp-page-2">
                <div class="madp-statistics-data">
                    <div class="madp-statistics-title">
                        <span>成员统计</span>
                        <el-popover placement="bottom-start" width="500" trigger="hover">
                            <div>
                                <p>1、成员总数:企业微信成员的总数量</p>
                                <p>2、在职人数:在职成员总数量</p>
                                <p>3、离职人数:离职人员总数量</p>
                                <p>4、客户总数:企业微信客户总数量</p>
                                <p>5、流失客户数:流失客户总数量</p>
                                <p>6、群数量:成员建立的客户群总数量</p>
                            </div>
                            <el-button type="text" slot="reference" style="margin-left: 20px">
                                统计说明
                                <i class="el-icon-question"></i>
                            </el-button>
                        </el-popover>
                    </div>
                    <statistics-card v-loading="pageLoading" :cardInfo="cardInfo" :cardData="basicInfo" />
                    <div class="madp-gap-wrap">
                        <div class="madp-flex madp-fle" v-if="tableType === 2">
                            <el-form label-width="100px" class="madp-flex">
                                <el-form-item label="成员名:">
                                    <el-input v-model.trim="searchForm.name" placeholder="请输入成员姓名"></el-input>
                                </el-form-item>
                            </el-form>
                            <div class="madp-ml10" style="min-width:fit-content">
                                <el-button type="primary" @click="handleSearch">搜索</el-button>
                                <el-button @click="handleReset">清空</el-button>
                            </div>
                        </div>
                        <div class="madp-statistics-table">
                            <el-table
                                :header-cell-style="{
                                    background: 'rgb(255, 191, 191)',
                                    color: 'rgb(44,44,44)',
                                }"
                                stripe
                                :data="dateTableData"
                                v-show="tableType === 1"
                                v-loading="tableLoading"
                            >
                                <el-table-column label="序号">
                                    <template slot-scope="scope">{{ (datePagination.current - 1) * datePagination.size + scope.$index + 1 }}</template>
                                </el-table-column>
                                <el-table-column prop="code" label="机构号">
                                    <template slot-scope="scope">{{ scope.row.code || '--' }}</template>
                                </el-table-column>
                                <el-table-column prop="name" label="机构名"></el-table-column>
                                <el-table-column prop="empTotal" label="成员总数"></el-table-column>
                                <el-table-column prop="empOnTotal" label="在职人数"></el-table-column>
                                <el-table-column prop="empLeaveTotal" label="离职人数"></el-table-column>
                                <el-table-column prop="contactTotal" label="客户总数"></el-table-column>
                                <el-table-column prop="contactLossTotal" label="流失客户数"></el-table-column>
                                <el-table-column prop="roomTotal" label="群数量"></el-table-column>
                            </el-table>
                            <el-table
                                :header-cell-style="{
                                    background: 'rgb(255, 191, 191)',
                                    color: 'rgb(44,44,44)',
                                }"
                                stripe
                                :data="dateTableData"
                                v-show="tableType === 2"
                                v-loading="tableLoading"
                            >
                                <el-table-column label="序号">
                                    <template slot-scope="scope">{{ (datePagination.current - 1) * datePagination.size + scope.$index + 1 }}</template>
                                </el-table-column>
                                <el-table-column prop="code" label="账号"></el-table-column>
                                <el-table-column prop="name" label="成员名"></el-table-column>
                                <el-table-column prop="contactTotal" label="客户总数"></el-table-column>
                                <el-table-column prop="contactLossTotal" label="流失客户数"></el-table-column>
                                <el-table-column prop="roomTotal" label="群数量"></el-table-column>
                            </el-table>
                            <!-- 列表分页 -->
                            <el-pagination
                                background
                                v-if="datePagination.total > 0"
                                class="madp-black-pagination"
                                @size-change="handleSizeChangeByDate"
                                @current-change="handleCurrentChangeByDate"
                                :current-page="datePagination.current"
                                :page-sizes="[10, 20, 30, 50, 100]"
                                :page-size="datePagination.size"
                                layout="total, sizes, prev, pager, next, jumper"
                                :total="datePagination.total"
                            ></el-pagination>
                        </div>
                    </div>
                </div>
                <div class="madp-statistics-chart">
                    <div class="madp-statistics-title">趋势图</div>
                    <div class="madp-gap-wrap">
                        <tabsTime ref="tabs1" :form="memberStatistics" :curDeptId="curDeptId" @changeViews="changeViews1" />
                    </div>
                </div>
                <!-- 折线图 -->
                <div id="madp-chart-e6" style="width: 100%; height: 400px; margin: 30px auto" v-show="lineChartOption.xAxis.data && lineChartOption.xAxis.data.length > 0"></div>
                <messageContent :curDeptId="curDeptId" :tableType="tableType" />
            </div>
        </div>
    </div>
</template>
<script>
import { fetchExcel } from '@/api/operation-manage/customer-statistics';
import { getCustomerTotal, getCustomerList, tendencyData } from '@/api/operation-manage/employee-statistics';
import messageContent from './message.vue';
import DownloadBtn from '@/components/download-btn/';
import StatisticsCard from '@/components/statistics-card/';
import { fetchTree } from '@/api/admin/dept';
import tabsTime from '@/components/tabs-time-choose';
export default {
    components: {
        messageContent,
        DownloadBtn,
        StatisticsCard,
        tabsTime,
    },
    data() {
        return {
            pageLoading: false,
            //日期禁用
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
            },
            basicInfo: [],
            channelCodeId: '',
            channelName: '',
            dimensionType: 1, //维度 客户总数、新增客户数、流失客户数、净增客户数
            dimensionTypeName: '客户总数',
            memberStatistics: [
                {
                    label: '成员总数',
                    value: 5,
                },
                {
                    label: '在职人数',
                    value: 6,
                },
                {
                    label: '离职人数',
                    value: 7,
                },
                {
                    label: '客户总数',
                    value: 8,
                },
                {
                    label: '群数量',
                    value: 10,
                },
            ],
            // 趋势图相关
            dateType: '', //日期选择
            dateTypes: [
                {
                    type: 0,
                    label: '昨日',
                },
                {
                    type: 1,
                    label: '近一周',
                },
                {
                    type: 2,
                    label: '近一个月',
                },
            ],
            dateRangeVal: ['2021-05-18', '2021-05-18'],
            employeeId: '',
            tendencyForm: {
                startTime: '',
                endTime: '',
            },
            employees: [], //活码关联的员工列表
            dateTableData: [],
            datePagination: {
                current: 1,
                size: 10,
            },
            //折线图数据
            lineChartOption: {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        // 坐标轴指示器，坐标轴触发有效
                        type: 'line', // 默认为直线，可选为:'line' | 'shadow'
                    },
                    formatter: '{b}<br>客户总数: {c}条',
                },
                xAxis: {
                    type: 'category',
                    data: [],
                },
                yAxis: {
                    name: '人数',
                    type: 'value',
                },
                series: [
                    {
                        name: '客户总数',
                        type: 'line',
                        data: [],
                        lineStyle: {
                            color: '#ED5555',
                        },
                        itemStyle: {
                            color: '#ED5555',
                        },
                    },
                ],
            },
            lineChartData: [],
            cardInfo: [
                {
                    label: '成员总数',
                    key: 'empTotal',
                    color: '#FFD700',
                },
                {
                    label: '在职人数',
                    key: 'empOnTotal',
                    color: 'rgb(123, 215, 0)',
                },
                {
                    label: '离职人数',
                    key: 'empLeaveTotal',
                    color: 'rgb(23, 115, 70)',
                },
                {
                    label: '客户总数',
                    key: 'contactTotal',
                    color: '#FF8C00',
                },
                {
                    label: '流失客户数',
                    key: 'contactLossTotal',
                    color: '#90EE90',
                },
                {
                    label: '群数量',
                    key: 'roomTotal',
                    color: 'rgb(223, 55, 70)',
                },
            ],
            tableType: 1,
            searchForm: {},
            defaultProps: {
                children: 'children',
                label: 'name',
            },
            treeData: [],
            height: '',
            curDeptId: '',
            tableLoading: false,
        };
    },
    filters: {},
    watch: {
        dateType(newVal, oldVal) {
            if (newVal === '') return;
            let endDate = new Date();
            let startDate = new Date();
            if (newVal === 0) {
                this.dateRangeVal = [startDate, endDate];
            } else if (newVal === 1) {
                startDate.setTime(endDate.getTime() - 3600 * 1000 * 24 * 6);
                this.dateRangeVal = [startDate, endDate];
            } else {
                startDate.setTime(endDate.getTime() - 3600 * 1000 * 24 * 29);
                this.dateRangeVal = [startDate, endDate];
            }
        },
    },
    created() {
        // dateType默认值为近一周
        this.dateType = 1;
        this.initTree();
    },
    methods: {
        initTree() {
            fetchTree().then((response) => {
                if (response.data.code === 0) {
                    this.treeData = response.data.data;
                    if (this.treeData.length > 0) {
                        this.clickNode = this.treeData;
                        this.handleNodeClick(this.treeData[0]);
                    }
                }
            });
        },
        formatDate(val) {
            let time = new Date(val * 1000);
            let y = time.getUTCFullYear();
            let m = time.getMonth() + 1 < 10 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1;
            let d = time.getDate() < 10 ? '0' + time.getDate() : time.getDate();

            return y + '-' + m + '-' + d;
        },
        //导出excel
        exportExcel() {
            let dto = {
                startTime: this.tendencyForm.startTime,
                endTime: this.tendencyForm.endTime,
                type: this.dimensionType,
                // employeeId: this.employeeId
            };
            fetchExcel(dto).then((res) => {
                const blob = new Blob([res.data], {
                    type: 'application/ms-excel',
                });
                const reader = new FileReader();
                reader.readAsDataURL(blob);
                reader.onload = (e) => {
                    const a = document.createElement('a');
                    a.download = '客户统计文件.xls';
                    a.href = e.target.result;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                };
            });
        },
        // 按日期查看 分页
        handleSizeChangeByDate(val) {
            this.datePagination.size = val;
            this.datePagination.current = 1;
            this.getCustomerList(1);
        },
        handleCurrentChangeByDate(val) {
            this.datePagination.current = val;
            this.getCustomerList(1);
        },
        handleSearch() {
            this.getCustomerList();
        },
        handleNodeClick(data) {
            this.pageLoading = true;
            this.curDeptId = data.id;
            this.tableType = data.children.length > 0 ? 1 : 2;
            if (this.tableType == 2) {
                this.searchForm = {
                    name: '',
                };
            } else {
                this.searchForm = {};
            }
            getCustomerTotal(data.id)
                .then((res) => {
                    this.pageLoading = false;
                    if (res.data.code != 0) return;
                    this.basicInfo = res.data.data;
                })
                .catch(() => {
                    this.pageLoading = false;
                });
            this.getCustomerList();
        },
        getCustomerList(data) {
            if (!data) {
                this.datePagination.current = 1;
                this.datePagination.size = 10;
            }
            let obj = {
                current: this.datePagination.current,
                size: this.datePagination.size,
                deptId: this.curDeptId,
            };
            if (this.searchForm.name) obj.name = this.searchForm.name;
            this.tableLoading = true;
            getCustomerList(obj)
                .then((res) => {
                    this.tableLoading = false;
                    if (res.data.code != 0) return;
                    this.dateTableData = res.data.data.records;
                    this.datePagination.total = res.data.data.total;
                })
                .catch(() => {
                    this.tableLoading = false;
                });
        },
        changeViews1(obj) {
            if (this.curDeptId != '') {
                tendencyData(obj).then((res) => {
                    if (res.data.code != 0) return;
                    let xAxisData = [],
                        seriesData = [],
                        arr = res.data.data;
                    arr.map((item) => {
                        xAxisData.push(item.time);
                        seriesData.push(item.number);
                    });
                    this.lineChartOption.xAxis.data = xAxisData;
                    this.lineChartOption.series[0].data = seriesData;
                    let name = '';
                    name = this.memberStatistics.filter((i) => {
                        return i.value === obj.type;
                    })[0].label;
                    this.lineChartOption.tooltip.formatter = `{b}<br>${name}: {c}`;

                    let echarts = require('echarts');

                    // 绘制图表
                    this.$nextTick(() => {
                        // 基于准备好的dom，初始化echarts实例
                        let myChart = echarts.init(document.getElementById('madp-chart-e6'));
                        myChart.setOption(this.lineChartOption);
                        window.addEventListener('resize', function() {
                            myChart.resize();
                        });
                    });
                });
            }
        },
        handleReset() {},
    },
};
</script>
<style lang="scss" scoped>
.madp-table-title {
    color: #333;
    font-size: 16px;
}
.madp-statistics-title {
    color: #333;
    font-weight: bold;
    font-size: 20px;
    margin-top: 20px;
    margin-bottom: 15px;
}
.madp-statistics-text {
    font-size: 12px;
    color: #666;
    padding-left: 5px;
}

.madp-horizontal-divider {
    width: 100%;
    height: 4px;
    margin: 20px 0;
    background-color: #f0f2f5;
}
.madp-gap-wrap {
    margin-top: 20px;
}
.madp-statistics-tabs {
    margin-top: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .madp-chart-form .el-form-item {
        margin-right: 20px;
        margin-bottom: 0;
    }
    .madp-date-select {
        width: 120px;
    }
    .el-date-editor--daterange.el-input__inner {
        width: 300px;
    }
    /deep/ .el-date-editor .el-range-separator {
        width: 25px !important;
    }
}
.madp-table-user-wrap {
    display: flex;
    align-items: center;
    .madp-table-avatar {
        display: block;
        width: 32px;
        height: 32px;
        object-fit: contain;
        margin-right: 10px;
        border-radius: 4px;
    }
    span.madp-table-avatar {
        background-color: #ed5555;
        text-align: center;
        line-height: 32px;
        color: #fff;
    }
}
/deep/ .el-button--primary.is-plain {
    background-color: #fff;
    border-color: #ed5555;
}
.madp-black-pagination {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    margin-top: 10px;
}
.madp-fle {
    justify-content: flex-end;
}
.madp-page-left {
    overflow-x: auto;
}
.filter-tree {
    overflow: auto;
    padding: 10px;
    min-width: fit-content;
    width: 100%;
}
.madp-page-1 {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 6px;
    width: 13%;
    margin-left: 10px;
    overflow: auto;
    position: fixed;
    height: calc(100vh - 7rem);
    background: #fff;
}
.madp-page-2 {
    overflow: auto;
    float: right;
    width: 84%;
    padding: 0px 20px;
    background: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 6px;
    /deep/ .el-card__body {
        padding: 0 20px 40px 20px;
    }
}
</style>
